<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Exception\Handler;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use Service\Code\Normal;
use Hyperf\HttpServer\Contract\RequestInterface;
use Service\MessageService\WebApiRequestLogService;

class AppExceptionHandler extends ExceptionHandler
{
    /**
     * @var RequestInterface
     */
    protected $request;
    
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger,RequestInterface $request)
    {
        $this->logger = $logger;
        $this->request = $request;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        //$this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        //$this->logger->error($throwable->getTraceAsString());
        $rt_start = microtime(true);
        //终止异常回话请求，抛出异常处理
        $this->stopPropagation();
        
        $url = (string)$this->request->getUri();
        
        //接口tps 处理耗时
        $request_used_time = bcsub((string)microtime(true),(string)$rt_start,3);
        
        //写入错误日志
        $response_data = [
            'errorMsg'  => $throwable->getMessage(),
            'errorLine' => $throwable->getLine(),
            'errorFile' => $throwable->getFile()
        ];
        
        //获取请求body
        $body = $this->request->getParsedBody();
        $logs = [
            'request_terminal'      => 3,//请求错误
            'request_url_hash'      => md5($url),
            'request_url'           => $url,
            'request_method'        => $this->request->getMethod(),
            'request_parameters'    => json_encode($body,JSON_UNESCAPED_UNICODE),
            'request_used_time'     => $request_used_time,
            'request_ip'            => getIp(),
            'response_code'         => 500,
            'response_msg'          => $throwable->getMessage(),
            'response_contents'     => json_encode($response_data,JSON_UNESCAPED_UNICODE),
            'request_time'          => time(),
        ];
        
        //发布日志队列
        WebApiRequestLogService::instance()->publishMsg($logs);
        return response()->json(Normal::returnCode(500,"系统繁忙，请稍后再试",[
            'errorMsg'  => $throwable->getMessage(),
            'errorLine' => $throwable->getLine(),
            'errorFile' => $throwable->getFile()
        ]));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
